package com.eig.orderweb.service.impl;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eig.common.entity.homepageentity.prefecture.EduCourse;
import com.eig.common.entity.order.TOrder;
import com.eig.common.vo.Result;
import com.eig.orderweb.config.Alipay;
import com.eig.orderweb.dao.TOrderCourseDao;
import com.eig.orderweb.dao.TOrderDao;
import com.eig.orderweb.service.PayService;
import com.eig.orderweb.vo.AliPayBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayServiceImpl implements PayService {
 
    /**日志对象*/
//    private static final Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
 
    @Autowired(required = false)
    private Alipay alipay;
    @Autowired(required = false)
    private TOrderDao tOrderDao;
    @Autowired(required = false)
    private TOrderCourseDao tOrderCourseDao;
    @Override
    public Result aliPay(String courseId, String memberId) throws AlipayApiException {
        //查询是否存在该订单
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        TOrder orders = tOrderDao.selectOne(wrapper);
        if (orders != null) {
            if (orders.getStatus() == 1) {
//                return new Result(5000, "该订单已创建,请先去支付", null);
                return new Result(5000, "该订单支付,无需再付款", null);
            } else {
//                System.out.println("商户订单号为{},订单名称为{},付款金额为{}" + outTradeNo + "//" + subject + "//" + totalAmount);
                //商户订单号
                String sb = "1";
                for (int i = 0; i < 19; i++) {
                    sb=sb+(int)(Math.random() * 10);
                }
                //订单名称
                EduCourse eduCourse = tOrderCourseDao.selectById(courseId);
                AliPayBean alipayBean = new AliPayBean();
                alipayBean.setOut_trade_no(sb);
                alipayBean.setSubject(eduCourse.getTitle());
                alipayBean.setTotal_amount(eduCourse.getPrice().toString());
//                logger.info("调用支付服务接口...");
                String pay = alipay.pay(courseId, alipayBean);
                System.out.println("payyy++++++"+pay);
                return new Result(2000,"支付页面",pay);
            }
        }return null;
    }
}